//
//  NotificationViewModel.swift
//  EarbudsFunctions
//
//  Created by 李然 on 2024/5/20.
//

import Foundation
import RxSwift

public class NotificationCellViewModel: DefaultSwitchCellViewModel {
    
    public var type: NotificationType = .other
    
    public required init(isEnabled: Bool, type: NotificationType) {
        super.init(isEnabel: isEnabled)
        self.type = type
    }
}

public class NotificationViewModel: ViewModel {

    public let items = BehaviorRelay<[NotificationCellViewModel]>(value: [])
    
    public override init() {
        
        super.init()
        
        Observable.combineLatest(BluetoothManager.shared.queryMessageConfig(), BluetoothManager.shared.queryMessageState())
            .subscribe(onNext: { [weak self] config, state in
                
                var viewModels: [NotificationCellViewModel] = []
                
                for (index, id) in config.enumerated() {
                    var enable = false
                    if state.count > index {
                        enable = state[index] == 1 ? true : false
                    }
                    guard let type = NotificationType(rawValue: id) else { continue }
                    let viewModel = NotificationCellViewModel(isEnabled: enable, type: type)
                    viewModel.switchChanged.subscribe(onNext: { [weak self] value in
                        guard let `self` = self else { return }
                        self.send(with: index, enable: value)
                    }).disposed(by: viewModel.rx.disposeBag)
                    
                    viewModels.append(viewModel)
                }
                
                self?.items.accept(viewModels)
                
            }).disposed(by: rx.disposeBag)
    }
    
    private func send(with index: Int, enable: Bool) {
        items.value[index].isEnabled.accept(enable)
        let state = self.items.value.map{ $0.isEnabled.value ? 1 : 0 }
        BluetoothManager.shared.setMessageState(state)
    }
}

